package com.mths.client.page;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.Widget;
import com.mths.client.component.Button;
import com.mths.client.component.ComboBox;
import com.mths.client.component.Div;
import com.mths.client.component.TextArea;
import com.mths.client.component.TextField;
import com.mths.client.constant.DirectorType;
import com.mths.client.constant.PageConstant;
import com.mths.client.controller.CompanyController;
import com.mths.client.controller.CompanyControllerAsync;
import com.mths.client.dto.CompanyInfoDTO;
import com.mths.client.dto.CompanySearchDTO;
import com.mths.client.dto.DirectorDTO;
import com.mths.client.dto.InspectorDTO;
import com.mths.client.util.AsyncCall;
import com.mths.client.util.ClientCacheUtil;
import com.mths.client.util.ClientConvertUtil;
import com.mths.client.util.PageUtil;
import com.mths.client.util.SmartCardUtil;
import com.mths.client.widget.DirectorWidget;
import com.mths.client.widget.InspectorWidget;
import com.mths.client.widget.MessageBox;

public class CompanyRegister extends AbstractPage implements IPage {

	private CompanyInfoDTO companyInfoDTO = new CompanyInfoDTO();
	private CompanySearchDTO companySearchDTO = new CompanySearchDTO();

	private static CompanyRegisterUiBinder uiBinder = GWT.create(CompanyRegisterUiBinder.class);

	interface CompanyRegisterUiBinder extends UiBinder<Widget, CompanyRegister> {
	}

	/**
	 * Create a remote service proxy to talk to the server-side Login service.
	 */
	private final CompanyControllerAsync companyService = GWT.create(CompanyController.class);

	@UiField
	TextField companyType, mersisNo, tradeName, companyCenter, committedCapital, paidCapital, phoneNo, faxNo, internetAddress, alias;

	@UiField
	TextArea contactAdress;

	@UiField
	Button saveBtn, addDirectorBtn, addInspectorBtn, closeBtn;

	@UiField
	ComboBox comboBox;

	@UiField
	TabPanel mainTab;

	@UiField
	Div directorWidgetDiv, inspectorWidgetDiv;

	private DirectorRegister directorRegisterPage;
	private InspectorRegister inspectorRegisterPage;

	public CompanyRegister() {
		initWidget(uiBinder.createAndBindUi(this));
		// create event handler
		createEventListener();
		// load component data
		loadComponentData();

	}

	private void loadComponentData() {
		comboBox.addItem(messages.DirectorType_real(), DirectorType.REAL.toString());
		comboBox.addItem(messages.DirectorType_corporate(), DirectorType.CORPORATE.toString());

		// true if user login
		companySearchDTO.setWithObjId(Boolean.TRUE);
		companySearchDTO.setAlias(ClientCacheUtil.instance().getSessionUser().getSelectedCompanyAlias());
		companyService.loadCompanyInfo(companySearchDTO, new AsyncCall<CompanyInfoDTO>() {
			@Override
			public void successCall(CompanyInfoDTO result) {
				companyInfoDTO = result;
				loadPageDatas();
			}
		});
	}

	private void createEventListener() {
		mainTab.selectTab(0, true);

		saveBtn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				saveCompany();
			}
		});

		addDirectorBtn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				addDirectorClicked();
			}
		});

		addInspectorBtn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				addIncspectorClicked();
			}
		});

		closeBtn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				PageUtil.navigationManager.controlOpenPageByFUrl(PageConstant.COMPANY_INFO);
			}
		});

		alias.addBlurHandler(new BlurHandler() {

			@Override
			public void onBlur(BlurEvent event) {
				alias.setFieldValue(ClientConvertUtil.convertUpperCaseUrl(alias.getFieldValue()));
			}
		});

		tradeName.addBlurHandler(new BlurHandler() {

			@Override
			public void onBlur(BlurEvent event) {
				tradeName.setFieldValue(ClientConvertUtil.convertUpperCaseTurkish(tradeName.getFieldValue()));
			}
		});
	}

	private void loadPageDatas() {
		loadCompanyInfos();
		loadDirectorsInfos();
		loadInspectorsInfos();
	}

	private void loadCompanyInfos() {
		if (companyInfoDTO == null || companyInfoDTO.getCompanyDTO() == null)
			return;
		companyType.setFieldValue(companyInfoDTO.getCompanyDTO().getCompanyType());
		mersisNo.setFieldValue(companyInfoDTO.getCompanyDTO().getMersisNo());
		tradeName.setFieldValue(companyInfoDTO.getCompanyDTO().getTradeName());
		alias.setFieldValue(companyInfoDTO.getCompanyDTO().getAlias());
		companyCenter.setFieldValue(companyInfoDTO.getCompanyDTO().getCompanyCenter());
		committedCapital.setFieldValue(companyInfoDTO.getCompanyDTO().getCommittedCapital());
		paidCapital.setFieldValue(companyInfoDTO.getCompanyDTO().getPaidCapital());
		phoneNo.setFieldValue(companyInfoDTO.getCompanyDTO().getPhoneNo());
		faxNo.setFieldValue(companyInfoDTO.getCompanyDTO().getFaxNo());
		internetAddress.setFieldValue(companyInfoDTO.getCompanyDTO().getInternetAddress());
	}

	private void loadDirectorsInfos() {
		// Director list
		directorWidgetDiv.clear();
		if (companyInfoDTO.getDirectorDtoList() != null) {
			for (DirectorDTO directorDTO : companyInfoDTO.getDirectorDtoList()) {
				DirectorWidget directorWidget = new DirectorWidget(directorDTO, Boolean.FALSE);
				directorWidget.setCompanyRegister(this);
				directorWidgetDiv.add(directorWidget);
			}
		}
	}

	private void loadInspectorsInfos() {
		// inspector list
		inspectorWidgetDiv.clear();
		if (companyInfoDTO.getInspectorDtoList() != null) {
			for (InspectorDTO inspectorDTO : companyInfoDTO.getInspectorDtoList()) {
				InspectorWidget inspectorWidget = new InspectorWidget(inspectorDTO, Boolean.FALSE);
				inspectorWidget.setCompanyRegister(this);
				inspectorWidgetDiv.add(inspectorWidget);
			}
		}
	}

	private void addDirectorClicked() {
		openDirectorCreatePopup();
		directorRegisterPage.changePageDirectorType(comboBox.getFieldValue());
	}

	public DirectorRegister openDirectorCreatePopup() {
		directorRegisterPage = (DirectorRegister) popupPage(PageConstant.DIRECTOR_REGISTER);
		pagePopupDialog.setText("Yönetici Ekleyin");
		directorRegisterPage.setCompanyRegister(this);
		pagePopupDialog.center();

		return directorRegisterPage;
	}

	private void addIncspectorClicked() {
		openInspectorCreatePopup();
	}

	public InspectorRegister openInspectorCreatePopup() {
		inspectorRegisterPage = (InspectorRegister) popupPage(PageConstant.INSPECTOR_REGISTER);
		inspectorRegisterPage.setCompanyRegister(this);
		pagePopupDialog.setText("Denetçi Ekleyin");
		pagePopupDialog.center();

		return inspectorRegisterPage;
	}

	private void saveCompany() {
		companyInfoDTO.getCompanyDTO().setCommittedCapital(committedCapital.getFieldValue());
		companyInfoDTO.getCompanyDTO().setCompanyCenter(companyCenter.getFieldValue());
		companyInfoDTO.getCompanyDTO().setCompanyType(companyType.getFieldValue());
		companyInfoDTO.getCompanyDTO().setContactAddress(contactAdress.getFieldValue());
		companyInfoDTO.getCompanyDTO().setFaxNo(faxNo.getFieldValue());
		companyInfoDTO.getCompanyDTO().setInternetAddress(internetAddress.getFieldValue());
		companyInfoDTO.getCompanyDTO().setMersisNo(mersisNo.getFieldValue());
		companyInfoDTO.getCompanyDTO().setPaidCapital(paidCapital.getFieldValue());
		companyInfoDTO.getCompanyDTO().setPhoneNo(phoneNo.getFieldValue());
		companyInfoDTO.getCompanyDTO().setTradeName(tradeName.getFieldValue());
		companyInfoDTO.getCompanyDTO().setAlias(alias.getFieldValue());
		// sign process
		companyInfoDTO.setSignableInput(companyInfoDTO.toString());
		companyInfoDTO.setSign(SmartCardUtil.signDocument(companyInfoDTO.getSignableInput()));

		companyService.saveUpdateCompany(companyInfoDTO, new AsyncCall<Boolean>() {

			@Override
			public void successCall(Boolean result) {
				new MessageBox("işleminiz başarılı olarak gerçekleştirilmiştir");
			}
		});
	}

	// call from director created update popup
	public void saveOrUpdateDirector(DirectorDTO dirDTO) {
		if (dirDTO == null)
			new MessageBox("Yönetici bilgisi boş olamaz, Hata alındı");
		if (dirDTO.getObjid() == null) {
			companyInfoDTO.getDirectorDtoList().add(dirDTO);
		} else {
			for (DirectorDTO directorDto : companyInfoDTO.getDirectorDtoList()) {
				if (directorDto.getObjid() != null && directorDto.getObjid().equals(dirDTO.getObjid())) {
					directorDto.setCompanyCenter(dirDTO.getCompanyCenter());
					directorDto.setDirectorType(dirDTO.getDirectorType());
					directorDto.setMersisNo(dirDTO.getMersisNo());
					directorDto.setName(dirDTO.getName());
					directorDto.setSurname(dirDTO.getSurname());
					directorDto.setTitle(dirDTO.getTitle());
					directorDto.setTradeName(dirDTO.getTradeName());
				}
			}
		}
		loadDirectorsInfos();
		pagePopupDialog.hide();
	}

	// call from directorwidget delete button
	public void deleteDirector(DirectorDTO dirDTO) {
		if (companyInfoDTO.getDirectorDtoList() != null) {
			int deletedIndex = -1;
			for (DirectorDTO directorDTO : companyInfoDTO.getDirectorDtoList()) {
				if (dirDTO.getObjid() != null && dirDTO.getObjid().equals(directorDTO.getObjid()))
					deletedIndex = companyInfoDTO.getDirectorDtoList().indexOf(directorDTO);
				else if (dirDTO.getTempKeyForClientDelete().equals(directorDTO.getTempKeyForClientDelete()))
					deletedIndex = companyInfoDTO.getDirectorDtoList().indexOf(directorDTO);
			}
			if (deletedIndex != -1)
				companyInfoDTO.getDirectorDtoList().remove(deletedIndex);
		}
	}

	// call from inspector created update popup
	public void saveOrUpdateInspector(InspectorDTO insDTO) {
		if (insDTO == null)
			new MessageBox("Denetçi bilgisi boş olamaz, Hata alındı");
		if (insDTO.getObjid() == null) {
			companyInfoDTO.getInspectorDtoList().add(insDTO);
		} else {
			for (InspectorDTO inspectorDTO : companyInfoDTO.getInspectorDtoList()) {
				if (inspectorDTO.getObjid() != null && inspectorDTO.getObjid().equals(insDTO.getObjid())) {
					inspectorDTO.setAddress(insDTO.getAddress());
					inspectorDTO.setName(insDTO.getName());
					inspectorDTO.setRegisteredBranch(insDTO.getRegisteredBranch());
					inspectorDTO.setSurname(insDTO.getSurname());
					inspectorDTO.setTitle(insDTO.getTitle());
				}
			}
		}
		loadInspectorsInfos();
		pagePopupDialog.hide();
	}

	// call from directorwidget delete button
	public void deleteInspector(InspectorDTO insDTO) {
		if (companyInfoDTO.getInspectorDtoList() != null) {
			int deletedIndex = -1;
			for (InspectorDTO inspectorDTO : companyInfoDTO.getInspectorDtoList()) {
				if (insDTO.getObjid() != null && insDTO.getObjid().equals(inspectorDTO.getObjid()))
					deletedIndex = companyInfoDTO.getInspectorDtoList().indexOf(inspectorDTO);
				else if (insDTO.getTempKeyForClientDelete().equals(inspectorDTO.getTempKeyForClientDelete()))
					deletedIndex = companyInfoDTO.getInspectorDtoList().indexOf(inspectorDTO);
			}
			if (deletedIndex != -1)
				companyInfoDTO.getInspectorDtoList().remove(deletedIndex);
		}
	}

	@Override
	public String pageName() {
		return messages.CompanyRegister_pageName();
	}
}
